package com.fanqiechaodan.proxy.cglibproxy;

import com.fanqiechaodan.proxy.cglibproxy.service.DemoInterface;
import com.fanqiechaodan.proxy.cglibproxy.service.DemoService;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

/**
 * @author fanqiechaodan
 * @Classname Main
 * @Description {https://blog.csdn.net/qq_43135259/article/details/129276917?spm=1001.2014.3001.5502}
 */
public class Demo {

    public static void main(String[] args) {
        final DemoService target = new DemoService();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(DemoService.class);
        // 必须设置callbacks不然会出现java.lang.NullPointerException
        enhancer.setCallbacks(new Callback[]{(MethodInterceptor) (o, method, objects, methodProxy) -> {

            // test方法增强逻辑
            if ("test".equals(method.getName())) {
                System.out.println("方法执行前增强...");
                Object res = method.invoke(target, objects);
                System.out.println("方法执行后增强...");
                return res;
            }

            // 其他方法正常执行
            return method.invoke(target, objects);
        }});
        DemoService demoService = (DemoService) enhancer.create();
        demoService.test();

        Enhancer enhancer1 = new Enhancer();
        enhancer1.setSuperclass(DemoInterface.class);
        enhancer1.setCallbacks(new Callback[]{(MethodInterceptor) (o, method, objects, methodProxy) -> {
            // test方法增强逻辑
            if ("test".equals(method.getName())) {
                System.out.println("切面逻辑...");
            }
            return null;
        }});
        DemoInterface demo = (DemoInterface) enhancer1.create();
        demo.test();
    }
}
